import { Actions, useStoreActions } from 'easy-peasy';
import { useEffect, useState } from 'react';

import TitledGreyBox from '@/components/elements/TitledGreyBox';
import { Button } from '@/components/elements/button/index';
import { Dialog } from '@/components/elements/dialog';

import { httpErrorToHuman } from '@/api/http';
import reinstallServer from '@/api/server/reinstallServer';

import { ApplicationStore } from '@/state';
import { ServerContext } from '@/state/server';

export default () => {
    const uuid = ServerContext.useStoreState((state) => state.server.data!.uuid);
    const [modalVisible, setModalVisible] = useState(false);
    const { addFlash, clearFlashes } = useStoreActions((actions: Actions<ApplicationStore>) => actions.flashes);

    const reinstall = () => {
        clearFlashes('settings');
        reinstallServer(uuid)
            .then(() => {
                addFlash({
                    key: 'settings',
                    type: 'success',
                    message: '您的服务器已开始重新安装过程。',
                });
            })
            .catch((error) => {
                console.error(error);

                addFlash({ key: 'settings', type: 'error', message: httpErrorToHuman(error) });
            })
            .then(() => setModalVisible(false));
    };

    useEffect(() => {
        clearFlashes();
    }, []);

    return (
        <TitledGreyBox title={'重装服务器'}>
            <Dialog.Confirm
                open={modalVisible}
                title={'确认重装'}
                confirm={'是的,现在重装'}
                onClose={() => setModalVisible(false)}
                onConfirmed={reinstall}
            >
                您确定,在此过程中,您的服务器将被停止,并且某些文件可能会被删除或修改 您想继续吗？
            </Dialog.Confirm>
            <p className={`text-sm`}>
                重新安装服务器将停止它,然后重新运行最初设置它的安装脚本 向上。&nbsp;
                <strong className={`font-medium`}>
                    在此过程中,某些文件可能会被删除或修改,请在之前备份您的数据 继续。
                </strong>
            </p>
            <div className={`mt-6 text-right`}>
                <Button.Danger variant={Button.Variants.Secondary} onClick={() => setModalVisible(true)}>
                    重装服务器
                </Button.Danger>
            </div>
        </TitledGreyBox>
    );
};
